package cn.xetsoft.supermarket.view;

import cn.xetsoft.supermarket.common.DataResponse;
import cn.xetsoft.supermarket.common.SystemData;
import cn.xetsoft.supermarket.dao.impl.GoodDaoImpl;
import cn.xetsoft.supermarket.entity.Cart;
import cn.xetsoft.supermarket.entity.Good;
import cn.xetsoft.supermarket.entity.User;
import cn.xetsoft.supermarket.service.Bean;
import cn.xetsoft.supermarket.service.GoodService;
import cn.xetsoft.supermarket.service.OrderService;
import cn.xetsoft.supermarket.service.impl.GoodServiceImpl;
import cn.xetsoft.supermarket.util.BigDecimalUtil;
import cn.xetsoft.supermarket.util.GUITools;
import cn.xetsoft.supermarket.util.PropertiesUtil;
import cn.xetsoft.supermarket.util.ViewDataUtil;
import cn.xetsoft.supermarket.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@SuppressWarnings("serial")

/**
 * 收银台窗口
 */
public  class CashierFrame extends JFrame{
    private ArrayList<Cart> shoppingCart; //购物车列表
    private List<Good> goodList;    //商品列表
    GoodService goodService = Bean.getGoodServiceInstance();
    private OrderService orderService = Bean.getOrderServiceInstance();
    //定义界面使用到的组件作为成员变量
    private JLabel TotalMoney = new JLabel();//总金额
    private JScrollPane goodsPane = new JScrollPane();//滚动视口
    private JScrollPane ShoppingCartPane = new JScrollPane();//滚动视口
    protected JTable Goodstable = new JTable(){
        public boolean isCellEditable(int rowIndex, int ColIndex){
            return false;
        }
    }; //商品列表
    protected JTable ShoppingCarttable = new JTable(){
        public boolean isCellEditable(int rowIndex, int ColIndex){
            return false;
        }
    }; //购物车列表
    private JButton createOrderBtn = new JButton();//场景订单按钮
    //背景图
    private JLayeredPane layeredPane;
    private ImageIcon image;
    private JPanel jp;
    private JLabel jl;
    //构造方法
    public CashierFrame() {
        this.init();// 初始化操作
        this.addComponent();// 添加组件
        this.addListener(this);// 添加监听器
        LodingGood(this.Goodstable);
        this.shoppingCart = new ArrayList<Cart>();
    }
    // 初始化操作
    private void init() {
        this.setTitle("收银台 - 熵客云超市管理");// 标题
        this.setSize(1300, 650);// 窗体大小与位置
        GUITools.center(this);//设置窗口在屏幕上的位置
        this.setResizable(false);// 窗体大小固定
    }
    // 添加组件
    private void addComponent() {
        layeredPane=new JLayeredPane();
        /**
         * 得到路径区别开发环境和jar包
         */
        String imgFile = "Images/CashierBgImg.png";
        if (!PropertiesUtil.getProperty("debug.resources.type").equals("jar")){
            imgFile = Class.class.getResource("/").getPath() + imgFile;
        }
        image=new ImageIcon(imgFile);//添加背景图
        //创建背景
        jp=new JPanel();
        jp.setBounds(0,-10,image.getIconWidth(),642);

        jl=new JLabel(image);
        jl.setBounds(0,0,image.getIconWidth(),642);
        jp.add(jl);

        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
        tcr.setHorizontalAlignment(SwingConstants.CENTER);// 设置table内容居中

        //商品表格
        Goodstable.getTableHeader().setReorderingAllowed(false);	//列不能移动
        Goodstable.getTableHeader().setResizingAllowed(false); 	//不可拉动表格
        Goodstable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        Goodstable.getTableHeader().setReorderingAllowed(false);
        Goodstable.setFillsViewportHeight(true);//确保表永远不会小于视图区
        Goodstable.setRowSelectionAllowed(true);//整行选择
        Goodstable.setDefaultRenderer(Object.class,tcr);
        goodsPane.setBounds(26, 107, 782, 506);
        goodsPane.setViewportView(Goodstable);//视口装入表格

        //购物车表格
        ShoppingCarttable.getTableHeader().setReorderingAllowed(false);	//列不能移动
        ShoppingCarttable.getTableHeader().setResizingAllowed(false); 	//不可拉动表格
        ShoppingCarttable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        ShoppingCarttable.getTableHeader().setReorderingAllowed(false);
        ShoppingCarttable.setFillsViewportHeight(true);//确保表永远不会小于视图区
        ShoppingCarttable.setRowSelectionAllowed(true);//整行选择
        ShoppingCarttable.setDefaultRenderer(Object.class,tcr);
        ShoppingCartPane.setBounds(821, 26, 441, 500);
        ShoppingCartPane.setViewportView(ShoppingCarttable);					//视口装入表格

        //金额标签
        Font f = new Font("宋体", Font.PLAIN,24); //设置字体
        TotalMoney.setBounds(950,510,100,120);
        TotalMoney.setFont(f);
        TotalMoney.setText(String.valueOf(0.00));

        //创建订单
        createOrderBtn.setMargin(new Insets(0,0,0,0));//将边框外的上下左右空间设置为0
        createOrderBtn.setIconTextGap(0);//将标签中显示的文本和图标之间的间隔量设置为0
        createOrderBtn.setBorderPainted(false);//不打印边框
        createOrderBtn.setBorder(null);//除去边框
        createOrderBtn.setFocusPainted(false);//除去焦点的框
        createOrderBtn.setContentAreaFilled(false);//除去默认的背景填充
        createOrderBtn.setBounds(1145,540,95,58);
        //将背景图放到最底层。
        layeredPane.add(jp,JLayeredPane.DEFAULT_LAYER);
        //将控件放到更高一层
        layeredPane.add(goodsPane,JLayeredPane.MODAL_LAYER);
        layeredPane.add(ShoppingCartPane,JLayeredPane.MODAL_LAYER);
        layeredPane.add(TotalMoney,JLayeredPane.MODAL_LAYER);
        layeredPane.add(createOrderBtn,JLayeredPane.MODAL_LAYER);

        this.setLayeredPane(layeredPane);
        this.setSize(image.getIconWidth(),667);
        this.setVisible(true);
        this.requestFocusInWindow();

    }
    // 添加监听器
    private void addListener(CashierFrame cashierFrame) {
        Goodstable.addMouseListener(
                new MouseListener() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        //把商品添加到购物车
                        if (Goodstable.getSelectedRowCount() == 0 || Goodstable.getSelectedColumnCount() == 0){
                            JOptionPane.showMessageDialog(null,"尚未选中任何商品!");
                            return;
                        }
                        SystemData systemData = new SystemData();
                        int selectedRow = Goodstable.getSelectedRow();
                        Object GoodNumber = Goodstable.getValueAt(selectedRow, 0);
                        System.out.println(Integer.valueOf(GoodNumber.toString()));
                        DataResponse<Good> goodDataResponse = goodService.queryById(Integer.valueOf(GoodNumber.toString()));
                        Good good = null;
                        //通过代理类判断是否成功
                        if (goodDataResponse.isSuccess()){//操作成功
                            good = goodDataResponse.getData();
                            System.out.println(good);
                        } else {
                            //不成功打印错误信息
                            System.out.println(goodDataResponse.getMsg());
                            JOptionPane.showMessageDialog(null,goodDataResponse.getMsg());
                        }

                        if (goodDataResponse.getData().getStock() <= 0 ){
                            JOptionPane.showMessageDialog(null,"库存不足");
                            return;
                        } else {
                            //减少库存
                            int i = Integer.valueOf(Goodstable.getValueAt(selectedRow, 5).toString());
                            if (i>0){
                                Goodstable.setValueAt(i-1,selectedRow,5);
                                for (Cart cart : shoppingCart) {
                                    if (good.getGoodname().equals(cart.getGoodname())){
                                        Integer quantity = cart.getQuantity();
                                        cart.setQuantity(quantity+1);
                                        adDCartGood(cashierFrame.ShoppingCarttable);
                                        cashierFrame.TotalMoney.setText(String.valueOf(getTotal()));
                                        return;
                                    }
                                }

                                User user = systemData.getUser();
                                Cart cart = new Cart();
                                cart.setGoodname(good.getGoodname());
                                cart.setGoodbrand(good.getGoodbrand());
                                cart.setInprice(good.getInprice());
                                cart.setSaleprice(good.getSaleprice());
                                cart.setType(good.getType());
                                cart.setQuantity(1);
                                cart.setAgent(user.getName());
                                shoppingCart.add(cart);
                                adDCartGood(cashierFrame.ShoppingCarttable);
                                cashierFrame.TotalMoney.setText(String.valueOf(getTotal()));
                            }else {
                                JOptionPane.showMessageDialog(null,"库存不足");
                            }
                        }

                    }

                    @Override
                    public void mousePressed(MouseEvent e) {

                    }

                    @Override
                    public void mouseReleased(MouseEvent e) {

                    }

                    @Override
                    public void mouseEntered(MouseEvent e) {

                    }

                    @Override
                    public void mouseExited(MouseEvent e) {

                    }
                }
        );
        ShoppingCarttable.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //把购物车的商品删除
                int selectedRow;
                Object GoodName;
                if (ShoppingCarttable.getSelectedRowCount() == 0 || ShoppingCarttable.getSelectedColumnCount() == 0){
                    JOptionPane.showMessageDialog(null,"尚未选中任何商品!");
                    return;
                }else {
                    selectedRow =  ShoppingCarttable.getSelectedRow();
                    GoodName = ShoppingCarttable.getValueAt(selectedRow, 1);
                }
                String s = GoodName.toString();

                for (int i = 0; i < shoppingCart.size(); i++) {
                    Cart cart = shoppingCart.get(i);
                    if (shoppingCart.get(i).getGoodname().trim().equals(s)){
                        Integer quantity = cart.getQuantity();
                        if (quantity>1){
                            cart.setQuantity(quantity-1);
                        }else{
                            shoppingCart.remove(i);
                        }
                        System.out.println(cashierFrame.Goodstable.getSelectedRowCount());
                        //增加库存
                        for (int j = 0; j < cashierFrame.Goodstable.getSelectedRowCount()+1; j++) {
                            System.out.println(j);
                            String s1 = cashierFrame.Goodstable.getValueAt(j, 1).toString();
                            System.out.println(s1);
                            System.out.println(cart.getGoodname());
                            if (cart.getGoodname().trim().equals(s1)){
                                int goodStock = Integer.parseInt(cashierFrame.Goodstable.getValueAt(j, 5).toString())+1;
                                cashierFrame.Goodstable.setValueAt(goodStock,j,5);
                            }
                        }
                    }
                }
                adDCartGood(cashierFrame.ShoppingCarttable);
                cashierFrame.TotalMoney.setText(String.valueOf(getTotal()));
                return;
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
        createOrderBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //创建订单
                List<Cart> carts = new ArrayList<Cart>();
                for (int i = 0; i < shoppingCart.size(); i++) {
                    //设置数据
                    Cart cartGood = shoppingCart.get(i);
                    Cart cart = new Cart();
                    cart.setGoodbrand(cartGood.getGoodbrand());
                    cart.setAgent(cartGood.getAgent());
                    cart.setInprice(cartGood.getInprice());
                    cart.setGoodname(cartGood.getGoodname());
                    cart.setQuantity(cartGood.getQuantity());
                    cart.setSaleprice(cartGood.getSaleprice());
                    cart.setType(cartGood.getType());
                    //添加购物车
                    carts.add(cart);

                }
                //通过服务结算创建订单
                DataResponse<OrderVo> response = orderService.insert(carts);
                if (response.isSuccess()){
                    JOptionPane.showMessageDialog(null,"结算成功");
                    //清除购物车
                    for (int i = 0; i < shoppingCart.size(); i++) {
                        shoppingCart.remove(0);
                    }
                    adDCartGood(cashierFrame.ShoppingCarttable);
                    TotalMoney.setText(String.valueOf(0.00));
                    LodingGood(Goodstable);
                } else {
                    JOptionPane.showMessageDialog(null,"结算失败");
                }

                shoppingCart.clear();
                adDCartGood(ShoppingCarttable);
            }
        });
    }

    //在页面加载的时候把商品数据加载到页面上
    public void LodingGood(JTable table){
        ViewDataUtil viewDataUtil = new ViewDataUtil();
        String[][] tbody = new String[0][];
        DataResponse<List<Good>> listDataResponse = goodService.queryAll();
        if (listDataResponse.isSuccess()){//操作成功
            goodList = listDataResponse.getData();
            tbody = viewDataUtil.GoodlistToArraysByCashier(goodList);
        } else {
            //不成功打印错误信息
            System.out.println(listDataResponse.getMsg());
        }
        String[] thead = new String[]{"商品编号","商品名称","商品品牌","商品单价(/元)","计价单位","库存"};
        TableModel dataModel = new DefaultTableModel(tbody, thead);
        table.setModel(dataModel);
    }

    public void adDCartGood(JTable table){
        ViewDataUtil viewDataUtil = new ViewDataUtil();
        String[][] tbody = new String[0][];
        tbody = viewDataUtil.CartlistToArrays(shoppingCart);

        String[] thead = new String[]{"商品品牌","商品名称","商品单价(/元)","计价单位","数量"};
        TableModel dataModel = new DefaultTableModel(tbody, thead);
        table.setModel(dataModel);
    }

    public BigDecimal getTotal(){
        BigDecimal total = new BigDecimal(0);
        for (Cart c : shoppingCart) {
            BigDecimal saleprice = c.getSaleprice();
            total = BigDecimalUtil.add(total.doubleValue(),BigDecimalUtil.mul(saleprice.doubleValue(),c.getQuantity().doubleValue()).doubleValue());
        }
        log.debug(total.toString());
        return total;
    }
}
